package org.glassunit.core.deploy;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import org.glassunit.core.util.FileUtils;

/**
 * File based module.
 * @author Frederic Müller
 */
public class FileModule extends Module {

    private final File file;

    /**
     * Creates a new file module for the given directory.
     * The module's name is determined by the directory name
     * @param file directory
     */
    public FileModule(final File file) {
        super("/");
        if (file == null) {
            throw new NullPointerException("Missing file parameter");
        }
        if (!file.isFile()) {
            throw new RuntimeException(String.format("File '%s' is not a file", file.getAbsolutePath()));
        }
        this.file = file;
    }

    @Override
    public Set<String> getFiles() {
        final Set<String> items = new HashSet<String>();
        items.add(file.getName());
        return items;
    }

    @Override
    public InputStream getFile(final String filename) throws IOException {
        if (file.getName().equals(filename)) {
            return new BufferedInputStream(new FileInputStream(file));
        } else {
            return super.getFile(filename);
        }
    }

    @Override
    public Long getFileSize(final String filename) {
        if (file.getName().equals(filename)) {
            return file.length();
        } else {
            return super.getFileSize(filename);
        }
    }

    @Override
    public boolean exists(final String filename) {
        if (file.getName().equals(filename)) {
            return true;
        }
        return super.exists(filename);
    }
}
